//
//  DicMainView.m
//  划词显示
//
//  Created by 盛超 on 2018/8/15.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "DicMainView.h"

#import "KYTestEngine.h"
#import "KYTestConfig.h"
#import "KYStartEngineConfig.h"
#import "KYPlayer.h"
#import "KYRecorder.h"
#import "SCVolumeView.h"

#import "DicHeaderView.h"
#import "DictRequest.h"
#import "ModelDic.h"
#import "DicSenTableView.h"
#import "UIView+DicUtils.h"
#import "SCDict.h"

static const NSInteger recordSecond = 3;
static int soundMeterCount = 10;
@interface DicMainView ()<DicHeaderViewDelegate,UIScrollViewDelegate>

@property (nonatomic,strong) DicHeaderView *headerView;
@property (nonatomic,strong) UIView *maskView;
@property (nonatomic,strong) UIScrollView *scrollView;

@property (nonatomic,strong) UIButton *recordBtn;
@property (nonatomic,strong) UIButton *replayBtn;
@property (nonatomic,strong) UILabel *scoreLabel;
@property (nonatomic,strong) SCVolumeView *volumeView;
@property (nonatomic, strong) NSMutableArray *soundMeters;
@property (nonatomic,assign) NSInteger testType;


@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,assign) CGFloat second;

@property (nonatomic,assign) BOOL isShowRecord;

@property (nonatomic,strong) ModelDic *model;


@end

@implementation DicMainView

- (instancetype)initWithTestType:(DictTestType)type isShowRecord:(BOOL)show {

    if (self = [super init]) {
       // self.backgroundColor = [UIColor blueColor];
        self.frame = CGRectMake(0,10,dic_Width-20,332*dic_ScalesH);
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        imageView.image = [UIImage imageNamed:@"LSDict.bundle/弹窗背景"];
        [self addSubview:imageView];
        
        DicHeaderView *headerView = [[DicHeaderView alloc] initWithFrame:CGRectMake(10,0, self.frame.size.width-20, 0.45*self.frame.size.height) ShowRecord:show];
        headerView.delegate = self;
        self.headerView = headerView;
        [self addSubview:headerView];
        
        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(10,self.headerView.y+self.headerView.height+5,self.width-20,self.height-self.headerView.height-15)];
        self.scrollView = scrollView;
        scrollView.delegate = self;
        scrollView.pagingEnabled = YES;
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:scrollView];
        
        //使用LSPlaySenBtn扩大按钮点击范围
        LSPlaySenBtn *btn = [[LSPlaySenBtn alloc] initWithFrame:CGRectMake(self.width-25*dic_ScalesW,10*dic_ScalesW, 14, 14)];
        [btn setImage:[UIImage imageNamed:@"LSDict.bundle/关闭图标"] forState:UIControlStateNormal];
        [self addSubview:btn];
        [btn addTarget:self action:@selector(closeMaskView) forControlEvents:UIControlEventTouchUpInside];
                
        self.soundMeters = [NSMutableArray array];
        if (type==DictTestType_Word) {
            self.testType = KYTestType_Word;
        } else if (type == DictColType_Sen) {
            self.testType = KYTestType_Sentence;
        }
        _isShowRecord = show;
    }
    
    return self;
}

- (void)setDictUrl:(NSString *)dictUrl {
    _dictUrl = dictUrl;
}

- (void)setDictParam:(NSDictionary *)dictParam {
    _dictParam = dictParam;
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:_dictParam options:NSJSONWritingPrettyPrinted error:&error];
    NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    _dictParam = @{@"DictString":json};

    //[self loadData];
}

- (void)loadData {
    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
//    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
//    hud.bezelView.color = [UIColor colorWithWhite:0.f alpha:0.f];
    
    DictRequest *request = [[DictRequest alloc] init];
    request.requestUrl = _dictUrl;
    request.requestParam = _dictParam;
    
    __weak typeof(self) weakSelf = self;
    [request requestGetMethodWithSuccess:^(id responseObject) {
        
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        
        weakSelf.model = [ModelDic yy_modelWithDictionary:json];
       
        dispatch_async(dispatch_get_main_queue(), ^{
            //跟读按钮
            if (weakSelf.isShowRecord) {
                [weakSelf addSubview:weakSelf.recordBtn];
            }
            
            //头部
            weakSelf.headerView.model = weakSelf.model;
            [MBProgressHUD hideHUDForView:weakSelf animated:YES];
            weakSelf.maskView.userInteractionEnabled = YES;
        });
        
    } Failure:^(NSError *error) {
        
    }];
}

#pragma mark - 动画效果
- (void)popAnimated:(BOOL)animated {
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = [UIColor colorWithWhite:0.f alpha:0.f];
    // 保存当前弹出的视图
    CGFloat halfScreenWidth = [[UIScreen mainScreen] bounds].size.width * 0.5;
    CGFloat halfScreenHeight = [[UIScreen mainScreen] bounds].size.height * 0.5;
    // 屏幕中心
    CGPoint screenCenter = CGPointMake(halfScreenWidth, halfScreenHeight);
    self.center = screenCenter;
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self.maskView];
    [keyWindow addSubview:self];
    self.maskView.userInteractionEnabled = NO;
    
    if (animated) {
        // 第一步：将view宽高缩至无限小（点）
        self.transform = CGAffineTransformScale(CGAffineTransformIdentity,
                                                CGFLOAT_MIN, CGFLOAT_MIN);
        
        [UIView animateWithDuration:0.3 animations:^{
            // 第二步： 以动画的形式将view慢慢放大至原始大小的1.2倍
            self.transform =
            CGAffineTransformScale(CGAffineTransformIdentity, 1.2, 1.2);
            
        } completion:^(BOOL finished) {
            
            [UIView animateWithDuration:0.2 animations:^{
                // 第三步： 以动画的形式将view恢复至原始大小
                self.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                [self loadData];
//                //跟读按钮
//                if (self.isShowRecord) {
//                    [self addSubview:self.recordBtn];
//                }
//                //头部
//                self.headerView.model = self.model;
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [MBProgressHUD hideHUDForView:self animated:YES];
//                    self.maskView.userInteractionEnabled = YES;
//                });
                
            }];
        }];
        
    }
}

- (void)closeAnimated:(BOOL)animated {
    if (animated) {
        [self.maskView removeFromSuperview];
         __weak typeof(self) weakSelf = self;
        [UIView animateWithDuration:0.2 animations:^{
            // 第一步： 以动画的形式将view慢慢放大至原始大小的1.2倍
            self.transform =
            CGAffineTransformScale(CGAffineTransformIdentity, 1.2, 1.2);
            
            
        } completion:^(BOOL finished) {
            
            [UIView animateWithDuration:0.3 animations:^{
                // 第二步： 以动画的形式将view缩小至原来的1/1000分之1倍
                self.transform = CGAffineTransformScale(
                                                        CGAffineTransformIdentity, 0.001, 0.001);
                
                //关闭词典时结束所有播放
                [weakSelf.headerView stopPlay];
                
            } completion:^(BOOL finished) {
                // 第三步： 移除
                [self removeFromSuperview];

                if(self.delegate  && [self.delegate respondsToSelector:@selector(colseDicMainView:)]) {
                    [self.delegate colseDicMainView:self];
                }
                
            }];
            
        }];
        
    } else {
        
        [self removeFromSuperview];
        [self.maskView removeFromSuperview];
    }
}

- (UIView *)maskView {
    if (!_maskView) {
        _maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height)];
        _maskView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.3];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeMaskView)];
        [_maskView addGestureRecognizer:tap];
    }
    return _maskView;
}

- (void)closeMaskView {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"LSDictColsePlayer" object:nil];
     [self closeAnimated:YES];
}

#pragma mark - HeaderViewDelegate
- (void)selectBtn:(UIButton *)selectBtn ScrollToIndex:(NSInteger)index {

    [self.scrollView setContentOffset:CGPointMake(index * (self.width-20), 0)];
}

- (void)showBtns:(NSArray *)isExisBtns {
    
    NSLog(@"time=%@",[NSDate date]);
    BOOL isMean = ((NSNumber*)isExisBtns[0]).boolValue;
    BOOL isColl = ((NSNumber*)isExisBtns[1]).boolValue;
    BOOL isDisc = ((NSNumber*)isExisBtns[2]).boolValue;
    BOOL isClass = ((NSNumber*)isExisBtns[3]).boolValue;
    
    NSInteger index = 0;
    if (isMean) {
        DicSenTableView *tableView = [[DicSenTableView alloc] initWithFrame:CGRectMake(0, 0,self.width-20,self.height-self.headerView.height-15) style:UITableViewStyleGrouped];
        tableView.moudelID = DictColType_Sen;
        tableView.modelDic =  self.headerView.model;
        [self.scrollView addSubview:tableView];
         index = index + 1;
    }
    
    if (isColl) {
        DicSenTableView *tableView = [[DicSenTableView alloc] initWithFrame:CGRectMake((self.width-20)*index, 0,self.width-20,self.height-self.headerView.height-15) style:UITableViewStyleGrouped];
        tableView.moudelID = DictColType_Coll;
        tableView.modelDic =  self.headerView.model;
        [self.scrollView addSubview:tableView];
         index = index + 1;
    }
    
    if (isDisc) {
        DicSenTableView *tableView = [[DicSenTableView alloc] initWithFrame:CGRectMake((self.width-20)*index,0,self.width-20,self.height-self.headerView.height-15) style:UITableViewStyleGrouped];
        tableView.moudelID = DictColType_Disc;
        tableView.modelDic =  self.headerView.model;
        [self.scrollView addSubview:tableView];
        index = index + 1;
    }
    
    if (isClass) {
        DicSenTableView *tableView = [[DicSenTableView alloc] initWithFrame:CGRectMake((self.width-20)*index,0,self.width-20,self.height-self.headerView.height-15) style:UITableViewStyleGrouped];
        tableView.moudelID = DictColType_Class;
        tableView.modelDic =  self.headerView.model;
        [self.scrollView addSubview:tableView];
        index = index + 1;
    }
    self.scrollView.contentSize = CGSizeMake((self.width-20)*index, 0);
    NSLog(@"time=%@",[NSDate date]);
}

#pragma mark - scrollDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSInteger index = scrollView.contentOffset.x/(self.width-20);
    
    NSMutableArray *array = [NSMutableArray array];
    if (self.headerView.meanBtn) {
        [array addObject:self.headerView.meanBtn];
    }
    if (self.headerView.collBtn) {
        [array addObject:self.headerView.collBtn];
    }
    if (self.headerView.discBtn) {
        [array addObject:self.headerView.discBtn];
    }
    if (self.headerView.classBtn) {
        [array addObject:self.headerView.classBtn];
    }
    
    for(NSInteger i = 0;i<array.count;i++) {
        UIButton *btn = array[i];
        if (index==i) {
            [btn setTitleColor:[UIColor colorWithRed:3.0/255 green:134.0/255 blue:235.0/255 alpha:1] forState:UIControlStateNormal];
            [UIView animateWithDuration:0.1 animations:^{
                 self.headerView.lineImageView.x = btn.x;
            }];
        } else {
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }

}

#pragma mark - 语音评测

//开始录音
- (void)startAction:(UIButton*)sender {
    
    sender.userInteractionEnabled = NO;
    
    [self startTestEngine];
    
    [self.replayBtn removeFromSuperview];
    [self.scoreLabel removeFromSuperview];
    [self addSubview:self.volumeView];
    
    self.second = recordSecond;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timeAnim) userInfo:nil repeats:YES];
}

- (void)timeAnim{
    self.second = self.second-0.01;
    if (self.second <= 0.00) {
        [self.timer invalidate];
        self.timer = nil;
        
         [[KYTestEngine sharedInstance] stopEngine];
         
         [self.volumeView removeFromSuperview];
         [self addSubview:self.replayBtn];
         self.recordBtn.userInteractionEnabled = YES;
    }
}

//开始语音评测
- (void)startTestEngine {
    
    //配置评测参数
    KYTestConfig *config = [[KYTestConfig alloc] init];
    config.coreType =  self.testType;
    config.refText =  self.headerView.model.cwName;
    config.phonemeOption = KYPhonemeOption_KK;
    config.audioType = @"wav";
    config.sampleRate = 16000;
    config.sampleBytes = 2;
    config.soundIntensityEnable = YES;
    
    __weak typeof(self) weakSelf = self;
    [[KYTestEngine sharedInstance] startEngineWithTestConfig:config result:^(NSString *testResult) {
        [weakSelf showResult:testResult];
    }];
}

//重播
- (void)playBack:(UIButton*)sender {
    [[KYTestEngine sharedInstance] playback];
}

//解析评测结果
- (void)showResult:(NSString *)result {
   // printf("%s\n", [result UTF8String]);
    if([result rangeOfString:@"errId"].length > 0) {  //错误回调
        
        //NSLog(@"result：%@",result);
        
    } else if ([result rangeOfString:@"sound_intensity"].length > 0) {  //音强回调
        NSError *error;
        NSData *rdata = [result dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
        CGFloat soundIntensity = [[resultDic objectForKey:@"sound_intensity"] floatValue];
        NSLog(@"音量：%f",soundIntensity/100.0f);
        //处理声音数据数组
        if (_soundMeters.count < soundMeterCount) {
            
            [_soundMeters addObject:[NSNumber numberWithFloat:soundIntensity]];
            
        } else {
            
            for(NSInteger index = 0 ; index < soundMeterCount-1 ; index++) {
                _soundMeters[index] = _soundMeters[index+1];
            }
            // 插入新数据
            _soundMeters[soundMeterCount - 1] = [NSNumber numberWithFloat:soundIntensity];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateMeters" object:_soundMeters];
        }
        
    } else {
        NSError *error;
        NSData *rdata = [result dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
        NSDictionary *jsonresult = [resultDic objectForKey:@"result"];
        if(self.testType == KYTestType_Word)
        {
            //显示结果
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *str = [NSString stringWithFormat:@"%@分",[jsonresult objectForKey:@"overall"]];
                self.scoreLabel.text = [NSString stringWithFormat:@"%@",str];
                [self addSubview:self.scoreLabel];
                
            });
            
        }
    }
}

- (UIButton *)recordBtn {
    if(!_recordBtn) {
        
        _recordBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.width-100*dic_ScalesW,10*dic_ScalesW,70,40)];
     
        [_recordBtn addTarget:self action:@selector(startAction:) forControlEvents:UIControlEventTouchUpInside];
        [_recordBtn setImage:[UIImage imageNamed:@"LSDict.bundle/跟读话咪"] forState:UIControlStateNormal];
    }
    return _recordBtn;
}

- (UILabel *)scoreLabel {
    if (!_scoreLabel) {
        _scoreLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.width-100*dic_ScalesW,10*dic_ScalesW+40,70,20)];
        _scoreLabel.font = [UIFont systemFontOfSize:13];
        _scoreLabel.textColor = [UIColor redColor];
        _scoreLabel.textAlignment = NSTextAlignmentCenter;
    }
    
    return _scoreLabel;
}

- (SCVolumeView *)volumeView {
    if (!_volumeView) {
        _volumeView = [[SCVolumeView alloc] initWithFrame:CGRectMake(self.width-95*dic_ScalesW,10*dic_ScalesW+40,60,20)];
    }
    
    return _volumeView;
}

- (UIButton *)replayBtn {
    if (!_replayBtn) {
        _replayBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.width-100*dic_ScalesW,10*dic_ScalesW+60,70,20)];
        _replayBtn.backgroundColor = [UIColor colorWithRed:26.0/255 green:169.0/255 blue:251.0/255 alpha:1];
        _replayBtn.layer.cornerRadius = 2;
        _replayBtn.layer.masksToBounds = YES;
        [_replayBtn addTarget:self action:@selector(playBack:) forControlEvents:UIControlEventTouchUpInside];
        [_replayBtn setTitle:@"重播" forState:UIControlStateNormal];
        _replayBtn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    }
    return _replayBtn;
}

    
@end
